package com.wisdom.core.netty.request;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import static io.netty.handler.codec.http.HttpUtil.is100ContinueExpected;

import java.net.URI;
import java.util.Map;

/**
 * @description: <handler request header>
 * @author: Leo
 * @date: 2021-08-23 16:51
 */
public class RequestHeaderHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private Map<String,String> headerMap;

    public RequestHeaderHandler(Map<String,String> headerMap){
        this.headerMap = headerMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        String uri = fullHttpRequest.uri();
        HttpMethod method = fullHttpRequest.method();
        HttpVersion httpVersion = fullHttpRequest.protocolVersion();
        if (is100ContinueExpected(fullHttpRequest)){
            ctx.write(new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.CONTINUE));
            return;
        }
        FullHttpRequest request = new DefaultFullHttpRequest(httpVersion, method,new URI(uri).toASCIIString());
        headerMap.forEach(request.headers() :: add);
        ctx.writeAndFlush(request);
    }
}
